<?php

namespace plugin\cms\app\bll;

use core\attribute\Template;
use support\Db;


/**
 * 标签文章
 */
class TagContent
{
    /**
     * 根据标签位查询
     *
     * @param integer $cid
     * @param string|array $tagids
     * @param integer $count
     * @return array
     */
    #[Template]
    public function selByTags(int $cid, string|array $tagids, int $siteid, int $count = 6): array
    {

        $tagids = is_string($tagids) ? explode(',', $tagids) : $tagids;

        $bllCategory = new Category();
        $tablename   = $bllCategory->getTableName($cid, $siteid);
        $bllCategory = new Category();
        $childcates  = $bllCategory->getDescendantsAndSelf($cid, $siteid);
        $cids        = array_column($childcates, 'id');

        return Db::table($tablename)
            ->leftJoin('cms_tag_content', $tablename . '.id', '=', 'cms_tag_content.contentid')
            ->whereIn('cms_tag_content.tagid', $tagids)
            ->whereIn('cms_tag_content.cid', $cids)
            ->limit($count)
            ->orderByDesc('tagcontentid')
            ->get([$tablename . '.*', 'cms_tag_content.id as tagcontentid'])
            ->map(function ($value) {
                return (array)$value;
            })
            ->toArray();
    }



    /**
     * 某文章所使用的标签IDs
     *
     * @param integer $contentid
     * @param integer $cid
     * @param integer $siteid
     * @return array
     */
    public function selTagidsByContentid(int $contentid, int $cid = 0, int $siteid = 0): array
    {
        $tags = Db::table('cms_tag_content')
            ->where('contentid', '=', $contentid)
            ->when($cid !== 0, function ($query) use ($cid) {
                return $query->where('cid', '=', $cid);
            })
            ->when($siteid !== 0, function ($query) use ($siteid) {
                return $query->where('siteid', '=', $siteid);
            })
            ->get()
            ->map(function ($value) {
                return (array)$value;
            })
            ->toArray();

        return  array_column($tags,  'tagid');
    }

    /**
     * 从标签内容表中删除文章
     *
     * @param string|array $contentid
     * @param integer $cid
     * @param integer $siteid
     * @return void
     */
    public function delContent(string|array $contentids, int $cid, int $siteid)
    {
        if (is_string($contentids)) {
            $contentids = explode(',', $contentids);
        }
        Db::table('cms_tag_content')
            ->whereIn('contentid',  $contentids)
            ->where('cid', '=', $cid)
            ->where('siteid', '=', $siteid)
            ->delete();
    }
}
